package com.google.gwt.sample.stockwatcher.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Collections;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
/**
 * @author Vanessa
 *
 */
public class StockWatcher implements EntryPoint {

	private VerticalPanel mainPanel = new VerticalPanel();
	private FlexTable stocksFlexTable = new FlexTable();
	private HorizontalPanel addPanel = new HorizontalPanel();
	private TextBox newSymbolTextBox = new TextBox();
	private Button addStockButton = new Button("Add");
	private Label lastUpdatedLabel = new Label();
	private Label numItemsLabel = new Label();
	private ArrayList<String> stocks = new ArrayList<String>();
	private static final int REFRESH_INTERVAL = 5000; // ms
	private Button btnShowCredits = new Button("Créditos");
	private HstoricoStockPrice histoPrice = new HstoricoStockPrice();
	

	// private VerticalPanel mainPanel = new VerticalPanel();

	/** * Entry point method. */
	public void onModuleLoad() {
		// TODO Create table for stock data. // TODO
		// FILA, COLUMNA, VALOR
		stocksFlexTable.setText(0, 0, "Symbol");
		stocksFlexTable.setText(0, 1, "Price");
		stocksFlexTable.setText(0, 2, "Change");
		stocksFlexTable.setText(0, 3, "Remove");
		// Add styles to elements in the stock list table.
		stocksFlexTable.setCellPadding(6);
		stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader");
		stocksFlexTable.addStyleName("watchList");
		stocksFlexTable.getCellFormatter().addStyleName(0, 1,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(0, 2,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(0, 3,
				"watchListRemoveColumn");

		// Assemble Add Stock panel. // TODO

		addPanel.add(newSymbolTextBox);
		addPanel.add(addStockButton);
		addPanel.add(btnShowCredits);
		addPanel.addStyleName("addPanel");

		// Assemble Main panel. // TODO
		mainPanel.add(stocksFlexTable);
		mainPanel.add(addPanel);
		mainPanel.add(lastUpdatedLabel);
		mainPanel.add(numItemsLabel);

		// Associate the Main panel with the HTML host page. // TODO
		RootPanel.get("stockList").add(mainPanel);

		// TODO Move cursor focus to the input box. // TODO
		newSymbolTextBox.setFocus(true);

		// Listen for mouse events on the Add button.
		addStockButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				addStock();
			}
		});

	//listen for mouse button events on the credits button
		btnShowCredits.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				showPopupCredits();
			}

			
		});
		
		// Listen for keyboard events in the input box.
		newSymbolTextBox.addKeyDownHandler(new KeyDownHandler() {
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					addStock();
				}
			}
		});

		// Move cursor focus to the text box.
		newSymbolTextBox.setFocus(true);

		// Setup timer to refresh list automatically.
		Timer refreshTimer = new Timer() {
			@Override
			public void run() {
				refreshWatchList();
			}
		};
		refreshTimer.scheduleRepeating(REFRESH_INTERVAL);

	}

	/**
	 * Add stock to FlexTable. Executed when the user clicks the addStockButton
	 * or presses enter in the newSymbolTextBox.
	 */
	private void addStock() {
		// TODO Auto-generated method stub
		final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
		newSymbolTextBox.setFocus(true);

		// Stock code must be between 1 and 10 chars that are numbers, letters,
		// or dots.
		if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
			Window.alert("'" + symbol + "' is not a valid symbol.");
			newSymbolTextBox.selectAll();
			return;
		}

		newSymbolTextBox.setText("");

		// TODO Don't add the stock if it's already in the table.
		if (stocks.contains(symbol))
			return;

		// TODO Add the stock to the table.
		int row = stocksFlexTable.getRowCount();
		stocks.add(symbol);
		stocksFlexTable.setText(row, 0, symbol);
		stocksFlexTable.setWidget(row, 2, new Label());
		stocksFlexTable.getCellFormatter().addStyleName(row, 1,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 2,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 3,
				"watchListRemoveColumn");

		// TODO Add a button to remove this stock from the table.
		Button removeStockButton = new Button("x");
		removeStockButton.addStyleDependentName("remove");
		removeStockButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				int removedIndex = stocks.indexOf(symbol);
				stocks.remove(removedIndex);
				stocksFlexTable.removeRow(removedIndex + 1);
			}
		});
		stocksFlexTable.setWidget(row, 3, removeStockButton);

		// TODO Get the stock price.
		refreshWatchList();
		
		

	}

	private void refreshWatchList() {
		// TODO Auto-generated method stub
		final double MAX_PRICE = 100.0; // $100.00
		final double MAX_PRICE_CHANGE = 0.02; // +/- 2%

		StockPrice[] prices = new StockPrice[stocks.size()];
		for (int i = 0; i < stocks.size(); i++) {
			double price = Random.nextDouble() * MAX_PRICE;
			double change = price * MAX_PRICE_CHANGE
					* (Random.nextDouble() * 2.0 - 1.0);

			StockPrice sp = new StockPrice(stocks.get(i), price, change);
		
			prices[i]=sp;
			histoPrice.addStockPrice(sp);
		}

		//updateTable(prices);
		
/**Ejercicio 1
 * **/
		
	   numItemsLabel.setText("Número de acciones: " + stocks.size());
	

	}

	/**
	 * Update the Price and Change fields all the rows in the stock table.
	 * 
	 * @param prices
	 *            Stock data for all rows.
	 */
	private void updateTable(StockPrice[] prices) {
		// TODO Auto-generated method stub
		for (int i = 0; i < prices.length; i++) {
			updateTable(prices[i]);
		}
		// Display timestamp showing last refresh.
		lastUpdatedLabel.setText("Last update : "
				+ DateTimeFormat.getMediumDateTimeFormat().format(new Date()));
		
//llamamos valorMax
		valorMaximo(prices);
		
		

	}

	/**
	 * Update a single row in the stock table.
	 * 
	 * @param price
	 *            Stock data for a single row.
	 */
	private void updateTable(StockPrice price) {
		// Make sure the stock is still in the stock table.
		if (!stocks.contains(price.getSymbol())) {
			return;
		}

		int row = stocks.indexOf(price.getSymbol()) + 1;

		// Format the data in the Price and Change fields.
		String priceText = NumberFormat.getFormat("#,##0.00").format(
				price.getPrice());
		NumberFormat changeFormat = NumberFormat
				.getFormat("+#,##0.00;-#,##0.00");
		String changeText = changeFormat.format(price.getChange());
		String changePercentText = changeFormat
				.format(price.getChangePercent());

		// Populate the Price and Change fields with new data.
		stocksFlexTable.setText(row, 1, priceText);
		Label changeWidget = (Label) stocksFlexTable.getWidget(row, 2);
		changeWidget.setText(changeText + " (" + changePercentText + "%)");

		// Change the color of text in the Change field based on its value.
		String changeStyleName = "noChange";
		if (price.getChangePercent() < -0.1f) {
			changeStyleName = "negativeChange";
		} else if (price.getChangePercent() >= 0.1f) {
			changeStyleName = "positiveChange";
		}

		changeWidget.setStyleName(changeStyleName);
		
		/**Ejercicio 3**/
		Label priceWidget = (Label) stocksFlexTable.getWidget(row, 1);
		Label incrementWidget = (Label) stocksFlexTable.getWidget(row, 4);
		Label servereIncrementWidget = (Label) stocksFlexTable.getWidget(row, 5);
		priceWidget.setText(priceText + " â‚¬");
		changeStyleName = "noChange";
		if (price.getPrice() < 50) {
			changeStyleName = "negativeChange";
		} else if (price.getPrice() >= 50) {
			changeStyleName = "positiveChange";
		}

		priceWidget.setStyleName(changeStyleName);
		/** Para el 5
		*/
		lastUpdatedLabel.setText("Last update : "
				+ DateTimeFormat.getFormat(
						DateTimeFormat.PredefinedFormat.DATE_TIME_MEDIUM)
						.format(new Date()));
		checkIncrement(price,incrementWidget);
	
	
	}
	/**Ejerccio 4
	 * */
	
	private void valorMaximo(StockPrice[] prices) {
		List <StockPrice>lsp = Arrays.asList(prices);
		
		StockPrice maxSp= Collections.max(lsp);
		StockPrice minSp= Collections.min(lsp);
		Double total=0.0;
		
		for(StockPrice sp: lsp){
			total +=sp.getPrice();
		}
		Double media= total / lsp.size();
	}
	
	
/**Ejercicio 5
 * 
 * */
	private void checkIncrement (StockPrice sp, Label incrementWidget){
		List <StockPrice>  lsp= histoPrice.getHistory(sp);
		incrementWidget.setText("");
		
		if (lsp != null && lsp.size() > 1) {
			StockPrice ultimo = lsp.get(lsp.size() - 1);
			StockPrice penultimo = lsp.get(lsp.size() - 2);
			
			Double priceUltimo = ultimo.getPrice();
			String strPriceUltimo = formatearDecimales(priceUltimo);
			Double pricePenultimo = penultimo.getPrice();
			String strPricePenultimo = formatearDecimales(pricePenultimo);
			Double incrementoPenultimo = pricePenultimo * 0.10;
			
			if( priceUltimo >= (pricePenultimo+incrementoPenultimo) ){
				incrementWidget.setText(strPricePenultimo+" "+strPriceUltimo+" X");
				
			}
		}
	}
	private String formatearDecimales(Double cant){
		String cantidad = NumberFormat.getFormat("#,##0.00").format(cant);
		return cantidad;
	}
	
	
/**Ejercicio 2
 * **/
	private void showPopupCredits(){
	String text="<p>Autor: Vanesa Jover <p>Framework Google Web Toolkit<p>Módulo: Desarrollo de aplicadiones en servidor.<p>CFGS Desarrollo de aplicaciones web";
	final PopupPanel popUpCredits= new PopupPanel();	
	popUpCredits.setTitle("Créditos");
	popUpCredits.setWidget(new HTML (text));
    
	
	popUpCredits.setWidth("500px");
	popUpCredits.setHeight("300px");
	popUpCredits.show();
	popUpCredits.center();
	popUpCredits.setGlassEnabled(true);
	

	
	

	}

}